package com.ruoyi.waterPrice.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.ruoyi.common.core.domain.base.datam.WiOrganB;
import com.ruoyi.common.core.domain.business.waterPrice.WiFarmacctY;
import com.ruoyi.common.core.domain.business.waterPrice.WiFeemodeY;
import com.ruoyi.common.core.domain.business.waterPrice.WiOrgacctY;
import com.ruoyi.common.core.enums.FeeKindEnum;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.business.BusinessUtils;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.waterPrice.mapper.WiFarmacctYMapper;
import com.ruoyi.waterPrice.mapper.WiFeemodeYMapper;
import com.ruoyi.waterPrice.mapper.WiOrgacctYMapper;
import com.ruoyi.waterPrice.service.IWiFarmacctYService;
import com.ruoyi.waterPrice.service.IWiOrgacctYService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 机构水费台账登记Controller
 *
 * @author ps
 * @date 2023-02-17
 */
@RestController
@RequestMapping("/WiOrgacctY")
public class WiOrgacctYController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WiOrgacctYController.class);

    @Autowired
    private IWiOrgacctYService wiOrgacctYService;
    @Autowired
    private IWiFarmacctYService wiFarmacctYService;
    @Autowired
    private WiFeemodeYMapper wiFeemodeYMapper;
    @Autowired
    private WiFarmacctYMapper wiFarmacctYMapper;
    @Autowired
    private WiOrgacctYMapper wiOrgacctYMapper;


    /**
     * 当年应缴实缴分析
     */
    @GetMapping("/orgFeeIncomeAnalys")
    public AjaxResult orgFeeIncomeAnalys(String year, String orgCd) {
        log.info("应缴实缴对比 入参：" + year + "=" + orgCd);
        //判断是按机构还是按农户
        WiFeemodeY wiFeemodeY = wiFeemodeYMapper.selectWiFeemodeYByModeYr(year);
        if (wiFeemodeY != null && FeeKindEnum.FRAM.getCode().equals(wiFeemodeY.getFeeKind())) {
            return AjaxResult.success(wiFarmacctYService.farmFeeIncomeAnalys(year, orgCd));
        } else {
            return AjaxResult.success(wiOrgacctYService.orgFeeIncomeAnalys(year, orgCd));
        }
    }

    /**
     * 历年应缴实缴分析
     */
    @GetMapping("/orgFeeIncomeHistoryAnalys")
    public AjaxResult orgFeeIncomeHistoryAnalys(String orgCd) {
        log.info("历年应缴实缴分析 入参：" + orgCd);
        ArrayList<WiOrgacctY> res = new ArrayList<>();
        String orgNm = wiOrgacctYMapper.selectOrgNm(orgCd);
        //五年内
        int curYear = BusinessUtils.getCurCalendar().get("year");
        for (int i = 9; i >= 0; i--) {
            //判断每年 按农户还是 按机构
            BigDecimal totalFee = new BigDecimal("0");
            BigDecimal payFee = new BigDecimal("0");
            BigDecimal saveFee = new BigDecimal("0");
            WiFeemodeY wiFeemodeY = wiFeemodeYMapper.selectWiFeemodeYByModeYr((curYear - i) + "");
            if (wiFeemodeY != null && FeeKindEnum.FRAM.getCode().equals(wiFeemodeY.getFeeKind())) {
                List<WiFarmacctY> wiFarmaccties = wiFarmacctYService.farmFeeIncomeAnalys((curYear - i) + "", orgCd);
                for (WiFarmacctY vo : wiFarmaccties) {
                    totalFee = totalFee.add(vo.getTotalFee());
                    payFee = payFee.add(vo.getPayFee());
                    saveFee = saveFee.add(vo.getSaveFee());
                }
                WiOrgacctY wiOrgacctY = new WiOrgacctY();
                wiOrgacctY.setTotalFee(totalFee);
                wiOrgacctY.setPayFee(payFee);
                wiOrgacctY.setSaveFee(saveFee);
                wiOrgacctY.setFeeYr((curYear - i) + "");
                wiOrgacctY.setOrdNm(orgNm);
                res.add(wiOrgacctY);
            } else {
                List<WiOrgacctY> wiOrgaccties = wiOrgacctYService.orgFeeIncomeHistoryAnalys(orgCd);
                for (WiOrgacctY vo : wiOrgaccties) {
                    totalFee = totalFee.add(vo.getTotalFee());
                    payFee = payFee.add(vo.getPayFee());
                    saveFee = saveFee.add(vo.getSaveFee());
                }
                WiOrgacctY wiOrgacctY = new WiOrgacctY();
                wiOrgacctY.setTotalFee(totalFee);
                wiOrgacctY.setPayFee(payFee);
                wiOrgacctY.setSaveFee(saveFee);
                wiOrgacctY.setFeeYr((curYear - i) + "");
                wiOrgacctY.setOrdNm(orgNm);
                res.add(wiOrgacctY);
            }
        }
        return AjaxResult.success(res);
    }

    /**
     * 获取下属机构
     */
    @GetMapping("/getChildOrg")
    public AjaxResult getChildOrg(String orgCd) {
        log.info("历年应缴实缴分析 入参：" + orgCd);
        List<WiOrganB> wiOrgaccties = wiOrgacctYService.getChildOrg(orgCd);
        return AjaxResult.success(wiOrgaccties);
    }

    /**
     * 机构水费收缴
     */
    @PostMapping("/payOrgFee")
    public AjaxResult payOrgFee(@Valid WiOrgacctY wiOrgacctY) throws Exception {
        log.info("机构水费收缴 入参：" + wiOrgacctY);
        int i = wiOrgacctYService.payOrgFee(wiOrgacctY);
        if (i == 1) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("水费收缴失败，请联系系统管理员~");
        }
    }


    /**
     * 查询机构水费台账登记列表
     */
    @RequiresPermissions("waterPrice:WiOrgacctY:list")
    @GetMapping("/list")
    public TableDataInfo list(WiOrgacctY wiOrgacctY) {
        startPage();
        //判断是按机构还是按农户
        String feeYr = StringUtils.isNotBlank(wiOrgacctY.getFeeYr()) ? wiOrgacctY.getFeeYr() : BusinessUtils.getCurCalendar().get("year") + "";
        String feeKind;
        WiFeemodeY wiFeemodeY = wiFeemodeYMapper.selectWiFeemodeYByModeYr(feeYr);
        if (wiFeemodeY != null && StringUtils.isNotBlank(feeYr) && StringUtils.isNotBlank(wiOrgacctY.getOrgCd())) {
            feeKind = wiFeemodeY.getFeeKind();
            if (FeeKindEnum.FRAM.getCode().equals(feeKind)) {
                List<WiFarmacctY> WiFarmacctYS = wiFarmacctYMapper.selectWiFarmacctYListByOrgCdAndYr(feeYr, wiOrgacctY.getOrgCd());
                PageDomain pageDomain = TableSupport.buildPageRequest();
                List<WiFarmacctY> collect = WiFarmacctYS.stream().skip((pageDomain.getPageNum() - 1) * pageDomain.getPageSize()).limit(pageDomain.getPageSize()).collect(Collectors.toList());
                for (WiFarmacctY vo : collect) {
                    String farmNm = wiFarmacctYMapper.getFarmNm(vo.getFarmCd());
                    if (StringUtils.isNotBlank(farmNm)) {
                        vo.setFarmNm(farmNm);
                    }
                    String operNm = wiFarmacctYMapper.getOperNm(vo.getLastOper());
                    if (StringUtils.isNotBlank(operNm)) {
                        vo.setLastOper(operNm);
                    }
                }
                return getDataTable(collect);
            } else {
                return getDataTable(wiOrgacctYMapper.selectWiOrgacctYList(wiOrgacctY));
            }
        } else {
            return getDataTable(new ArrayList<>());
        }
    }

    /**
     * 导出机构水费台账登记列表
     */
    @RequiresPermissions("waterPrice:WiOrgacctY:export")
    @Log(title = "机构水费台账登记", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WiOrgacctY wiOrgacctY) {
        String feeKind;
        String feeYr = StringUtils.isNotBlank(wiOrgacctY.getFeeYr()) ? wiOrgacctY.getFeeYr() : BusinessUtils.getCurCalendar().get("year") + "";
        WiFeemodeY wiFeemodeY = wiFeemodeYMapper.selectWiFeemodeYByModeYr(feeYr);
        feeKind = wiFeemodeY.getFeeKind();
        if (FeeKindEnum.FRAM.getCode().equals(feeKind)) {
            List<WiFarmacctY> list = (List<WiFarmacctY>) this.list(wiOrgacctY).getRows();
            ExcelUtil<WiFarmacctY> util = new ExcelUtil<WiFarmacctY>(WiFarmacctY.class);
            util.exportExcel(response, list, "农户水费台账登记数据");
        }else{
            List<WiOrgacctY> list = wiOrgacctYService.selectWiOrgacctYList(wiOrgacctY);
            ExcelUtil<WiOrgacctY> util = new ExcelUtil<WiOrgacctY>(WiOrgacctY.class);
            util.exportExcel(response, list, "机构水费台账登记数据");
        }
    }

    /**
     * 获取机构水费台账登记详细信息
     */
    @RequiresPermissions("waterPrice:WiOrgacctY:query")
    @GetMapping(value = "/{feeYr}/{orgCd}")
    public AjaxResult getInfo(@PathVariable("feeYr") String feeYr, @PathVariable("orgCd") String orgCd) {
        return success(wiOrgacctYService.selectWiOrgacctYByFeeYrAndOrgCd(feeYr, orgCd));
    }

//    /**
//     * 新增机构水费台账登记
//     */
//    @RequiresPermissions("waterPrice:WiOrgacctY:add")
//    @Log(title = "机构水费台账登记", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody WiOrgacctY wiOrgacctY)
//    {
//        return toAjax(wiOrgacctYService.insertWiOrgacctY(wiOrgacctY));
//    }

    /**
     * 修改机构水费台账登记
     */
    @RequiresPermissions("waterPrice:WiOrgacctY:edit")
    @Log(title = "机构水费台账登记", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WiOrgacctY wiOrgacctY) {
        return toAjax(wiOrgacctYService.updateWiOrgacctY(wiOrgacctY));
    }

    /**
     * 删除机构水费台账登记
     */
    @RequiresPermissions("waterPrice:WiOrgacctY:remove")
    @Log(title = "机构水费台账登记", businessType = BusinessType.DELETE)
    @DeleteMapping("/{feeYrs}")
    public AjaxResult remove(@PathVariable String[] feeYrs) {
        return toAjax(wiOrgacctYService.deleteWiOrgacctYByFeeYrs(feeYrs));
    }
}
